# edited by levi_jia @云台二维码追踪
from maix import image, camera, display,touchscreen,uart,time
import struct

device = "/dev/ttyS0"
serial0 = uart.UART(device, 115200)

cam = camera.Camera(360, 240)
disp = display.Display()
img = image.Image(disp.width(), disp.height())

def send_four_uchar(c1,c2):
    sentdata = struct.pack(">BhhB",#大端模式
                   0xAB,
                   c1,
                   c2,
                   0xBA
                   )
    serial0.write(sentdata)
    print(sentdata)
    unpacked_data = struct.unpack(">BhhB", sentdata)
    print(unpacked_data)
    
while 1:
    img = cam.read()
    qrcodes = img.find_qrcodes()
    for a in qrcodes:
        rect = a.rect()
        # print(rect)
        img.draw_rect(rect[0], rect[1], rect[2], rect[3], image.Color.from_rgb(0,0,255))
        cx,cy = rect[0]+(rect[2]/2) , rect[1]+(rect[3]/2)
        img.draw_cross(int(cx), int(cy),image.Color.from_rgb(0,255,0),5,1)
        img.draw_string(a.x() + a.w() + 5, rect[1] + 20, "pl: " + a.payload(), image.Color.from_rgb(0,0,255))
        # print(cx,cy)
        if (cx<180):
            cx = -(180-cx)
        elif (cx>180):
            cx = cx-180
        else:
            cx = 0

        if (cy<120):
            cy = (120-cy)
        elif (cy>120):
            cy = -(cy-120)
        else:
            cy = 0  
        img.draw_string(rect[0], rect[1], str(cx)+" "+str(cy) , image.Color.from_rgb(0,255,0),2)
        send_four_uchar(int(cx),int(cy))
    if not qrcodes:
        send_four_uchar(0,0)
    disp.show(img)